package com.cmd.user;

import com.alibaba.fastjson.JSONObject;
import com.player.CommonUser;
import com.player.User;
import com.qy.util.RedisPoolMgr;
import com.qy.util.StaticData;
import com.util.AbstractCommand;
import com.util.PBMessage;

public class PhoneBindCMD  extends AbstractCommand{

	@Override
	public void execute(User user, PBMessage packet) throws Exception {
		JSONObject reJs = new JSONObject();
		reJs.put(StaticData.reKey.cmd.getKey(),packet.getCode());
		JSONObject param = packet.getMessage();
		if(!param.containsKey("phone")||!param.containsKey("vCode")){
			reJs.put(StaticData.reKey.code.getKey(), StaticData.codeType.param_error.getType());
			user.sendPacket(reJs);
			return;
		}
		String phone = param.getString("phone");
		//用户输入的验证码
		String vCode = param.getString("vCode");
		//服务器保存的验证码
		String mCode = (String) RedisPoolMgr.get(user.getKey()+phone, String.class);
		/*
		 * 判断验证码是否正确
		 * 不正确则错误次数+1
		 * 正确则错误次数清零
		 */
		Object tmp =  RedisPoolMgr.hashGet(StaticData.REDISKEY.V_CODE_ERROR.toString(), user.getKey());
		if(!vCode.equals(mCode)){
			int count = 0;
			if(tmp!=null&&!tmp.equals("null")){
				count = ((int) tmp)+1;
			}
			RedisPoolMgr.hashSet(StaticData.REDISKEY.V_CODE_ERROR.toString(), user.getKey(), count,3*60);
			reJs.put(StaticData.reKey.code.getKey(), StaticData.codeType.verify_error.getType());
			user.sendPacket(reJs);
			return;
		}else{
			if(tmp!=null&&!tmp.equals("null")){
				RedisPoolMgr.hashDel(StaticData.REDISKEY.V_CODE_ERROR.toString(), user.getKey());
			}
		}
		CommonUser commonUser = (CommonUser) user;	
		commonUser.getUserInfo().setPhone(phone);
		commonUser.getUserInfo().setUserStatus(StaticData.userStatus.normal.getType());
		reJs.put(StaticData.reKey.code.getKey(), StaticData.codeType.ok.getType());
		reJs.put(StaticData.reKey.cmd.getKey(),packet.getCode());
		user.sendPacket(reJs);
		return;
	}

}
